package com.chenwang.measure.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chenwang.measure.R;
import com.chenwang.measure.base.BaseActivity;
import com.chenwang.measure.model.Constant;
import com.chenwang.measure.model.ObserverOnNext;

import com.chenwang.measure.model.bean.CustomBean;
import com.chenwang.measure.model.bean.DataBean;
import com.chenwang.measure.model.bean.UploadBean;
import com.chenwang.measure.model.bean.WorkBean;
import com.chenwang.measure.ui.adapter.FreedomAdapter;
import com.chenwang.measure.ui.adapter.TaskManageAdapter;
import com.chenwang.measure.utils.FileUtils;
import com.chenwang.measure.utils.MyLogger;
import com.chenwang.measure.utils.MyToast;
import com.chenwang.measure.utils.RxUtils;
import com.chenwang.measure.utils.SharePreferenceUtils;
import com.chenwang.measure.utils.TimeUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import okhttp3.Response;


//自定义测量
public class FreedomActivity extends BaseActivity implements BaseQuickAdapter.OnItemChildClickListener {

    @BindView(R.id.rv)
    RecyclerView mRv;
    @BindView(R.id.et_start)
    EditText mEtStart;//开始
    @BindView(R.id.et_end)
    EditText mEtEnd;//结束
    private String mStart;
    private String mEnd;
    private List<CustomBean> mList = new ArrayList<>();//
    private FreedomAdapter mAdapter;

    @Override
    public int setLayoutId() {
        return R.layout.activity_freedom;
    }

    @Override
    public void initData() {
        super.initData();
        ButterKnife.bind(this);
        initRecyclerView();
    }
    private void initRecyclerView(){
        showLoading("正在加载数据");
        //获取json字符串
        String json = SharePreferenceUtils.getString(this,"custom_measure" ,"" );
        MyLogger.i(json);
        if (!TextUtils.isEmpty(json)){
            Gson gson = new Gson();//json转为List
            Type type = new TypeToken<List<CustomBean>>(){}.getType();
            mList = gson.fromJson(json, type);
        }
        mRv.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new FreedomAdapter(mList);
        mAdapter.setOnItemChildClickListener(this);
        mAdapter.openLoadAnimation(BaseQuickAdapter.SLIDEIN_RIGHT);
        mRv.setAdapter(mAdapter);
        dismissLoading();
    }


    @OnClick({R.id.btn,R.id.tv_setting,R.id.btn_uploading ,R.id.btn_delete})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_delete:
                delete();
                break;
            case R.id.tv_setting:
                startActivity(new Intent(this, SettingActivity.class));
                break;
            case R.id.btn:
                create();
                break;
            case R.id.btn_uploading:
                uploading();
                break;
        }
    }


//删除
    private void delete(){
        final List<CustomBean> list = new ArrayList<>();
        //遍历list中选中的条
        for (CustomBean customBean:mList){
            if (customBean.getState()==2)
                if (customBean.isSelect()){
                    list.add(customBean);
                }
        }
        int size = list.size();//获取选中的数量
        String name = SharePreferenceUtils.getString(this,"username" ,"" );
        final String ip = SharePreferenceUtils.getString(this,"ip" ,"" );
        if (TextUtils.isEmpty(name)){
            MyToast.show("请在设置里填写姓名");
        } else  if(TextUtils.isEmpty(ip)) {
            MyToast.show("请在设置里填写服务器ip");
        } else if (size ==0) {
            MyToast.show("没有要删除的测量");
        }else {
            showLoading("正在删除");
            mList.removeAll(list);
            mAdapter.replaceData(mList);
            //将数据保存json串 Sp中
            Gson gson = new Gson();
            String json = gson.toJson(mList);
            SharePreferenceUtils.putString(
                    FreedomActivity.this, "custom_measure", json);
            MyToast.show("删除成功");
            dismissLoading();


        }
    }

//上传
    private void uploading(){
        //遍历list中选中
      final List<CustomBean> list = new ArrayList<>();
      for (CustomBean customBean:mList){
          if (customBean.getState()==1)
          if (customBean.isSelect()){
              list.add(customBean);
          }
      }
      int size = list.size();//获取选中的数量
      String name = SharePreferenceUtils.getString(this,"username" ,"" );
      final String ip = SharePreferenceUtils.getString(this,"ip" ,"" );
      if (TextUtils.isEmpty(name)){
            MyToast.show("请在设置里填写姓名");
      } else  if(TextUtils.isEmpty(ip)) {
          MyToast.show("请在设置里填写服务器ip");
      } else if (size ==0) {
          MyToast.show("没有要上传的测量");
      }else {
          showLoading("正在上传");
          Gson gson = new Gson();
          final String json = gson.toJson(list);
          Observable.create(new ObservableOnSubscribe<Boolean>() {
              @Override
              public void subscribe(ObservableEmitter<Boolean> emitter) throws Exception {
                 /* Gson gson = new Gson();
                  ConfigBean configBean = new ConfigBean();
                  configBean.setIp(ip);
                  configBean.setState("2");
                  String json = gson.toJson(configBean);
                  MyLogger.i(json);
                  if (FileUtils.writeFile1(Constant.pathFile,"config.txt",json,false)) {
                      if (FileUtils.writeFile(Constant.pathFile + Constant.freeUploadingFile, json, false)) {
                          emitter.onNext(true);
                      }else {
                          emitter.onNext(false);
                      }
                  }else {
                      emitter.onNext(false);
                  }
*/
                 MyLogger.i(json);
                  Response response =OkGo.<String>post("http://"+ip+"/app/open/addFreeMode")
                          .upJson(json)
                          .execute();
                  String s = response.body().string();
                  System.out.println(s);
                  Gson gson = new Gson();
                  DataBean dataBean = gson.fromJson(s, DataBean.class);
                  if (dataBean.getCode() == 0){
                      MyToast.show(dataBean.getMsg());
                      emitter.onNext(true);
                  }else {
                      MyToast.show(dataBean.getMsg());
                      emitter.onNext(false);
                  }

              }
          }).compose(RxUtils.<Boolean>io_main()).subscribe(new ObserverOnNext<Boolean>() {
              @Override
              public void onNext(Boolean bool) {
                      if (bool){
                          //将上传成功状态设为 2 已完成
                          for (int i=0; i<mList.size();i++){
                              for (CustomBean customBean: list){
                                   if (customBean.getCreatorDate().equals(mList.get(i).getCreatorDate())){
                                       mList.get(i).setState(2);
                                   }
                              }

                          }
                          mAdapter.replaceData(mList);
                          Gson gson = new Gson();
                          String json = gson.toJson(mList);
                          SharePreferenceUtils.putString(
                                  FreedomActivity.this, "custom_measure", json);
                          MyToast.show("上传成功");
                      }else {

                      }
                      dismissLoading();
              }

          });

      }
    }


    //创建一条测量段
    private void create(){
        showLoading("正在创建");
        mStart = mEtStart.getText().toString();
        mEnd = mEtEnd.getText().toString();
        String name = SharePreferenceUtils.getString(this, "username", "");
        if (TextUtils.isEmpty(mStart)) {
            MyToast.show("起始点不能为空");
        } else if (TextUtils.isEmpty(mEnd)) {
            MyToast.show("结束点不能为空");
        } else if (TextUtils.isEmpty(name)) {
            MyToast.show("姓名不能为空");
        } else {
             CustomBean customBean = new CustomBean(mStart, mEnd, name, TimeUtils.getTodayDate("yyyy-MM-dd HH:mm:ss"));
             mList.add(0,customBean );

             Gson gson = new Gson();
             String json = gson.toJson(mList);
                SharePreferenceUtils.putString(
                        FreedomActivity.this, "custom_measure", json);
             mAdapter.replaceData(mList);
             MyToast.show("创建成功");

        }
        dismissLoading();
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
            switch (mList.get(position).getState()){
                case 0:
                    Intent intent = new Intent(this, CustomActivity.class);
                    intent.putExtra("data", mList.get(position));
                    startActivityForResult(intent,1 );
                    break;
                case 1:
                    MyToast.show("待上传");
                    break;
                case 2:
                    MyToast.show("已完成");
                    break;

            }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode ==1){
            if (resultCode ==2){//将测量成功的数据保存sp中 并更新
                CustomBean customBean = data.getParcelableExtra("data");
                for (int i =0; i< mList.size() ;i++){
                    if (mList.get(i).getCreatorDate().equals(customBean.getCreatorDate())){
                        mList.set(i, customBean);
                        break;
                    }
                }
                mAdapter.replaceData(mList);
                Gson gson = new Gson();
                String json = gson.toJson(mList);
                SharePreferenceUtils.putString(
                        FreedomActivity.this, "custom_measure", json);
            }
        }
    }
}
